package com.xgjweb.fsi.service;

import java.util.List;

import com.xgjweb.common.dao.ICommonDao;
import com.xgjweb.common.service.CommonServiceImpl;
import com.xgjweb.common.utils.XgjWebLogger;
import com.xgjweb.common.utils.XgjWebUtils;
import com.xgjweb.fsi.domain.Condition;
import com.xgjweb.fsi.domain.Message;
import com.xgjweb.fsi.domain.User;
import com.xgjweb.fsi.dto.MessageDto;

/**
 * 
 * @author xgj
 * 
 */
@SuppressWarnings("unchecked")
public class MessageServiceImpl extends CommonServiceImpl implements
		IMessageService {
	private ICommonDao messageDao;

	public void setMessageDao(ICommonDao messageDao) {
		this.messageDao = messageDao;
	}

	/**
	 * 添加留言
	 * 
	 * @param message
	 * @return
	 * @throws Exception
	 */
	public List<Message> addMessage(Message message) throws Exception {
		try {
			message.setStatementName("insertMessage");
			messageDao.insert(message);
			return queryMessage(message);
		} catch (Exception e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * 查旬留言
	 */
	public List<Message> queryMessage(Message message) throws Exception {
		try {
			message.setStatementName("queryMessageCount");
			Integer dataCount = (Integer) messageDao.selectByObject(message);
			message.setStatementName("queryMessage");
			List<Message> messageList = messageDao.selectByList(message);
			if (messageList.size() > 0) {
				Message m = messageList.get(0);
				m.setCondition(message.getCondition());
				m.getCondition().setDataCount(dataCount);
				User user;
				for (Message msg : messageList) {
					user = new User();
					if (msg.getUser_id() != null && msg.getUser_id() != 0) {
						user.setId(msg.getUser_id());
						user.setStatementName("selectUserByID");
						user = (User) messageDao.selectByObject(user);
						msg.setUser(user);
					} else {
						user.setName("匿名");
						user.setPicture("default.jpg");
						msg.setUser(user);
					}
				}
			}
			return messageList;
		} catch (Exception e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * 查找留言
	 * 
	 * @return
	 * @throws Exception
	 */
	public MessageDto findMessageIndex() throws Exception {
		try {
			MessageDto messageDto = new MessageDto();
			messageDto.setStatementName("findMessageForIndex");
			messageDto = (MessageDto) messageDao.selectByObject(messageDto);
			return messageDto;
		} catch (RuntimeException e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}
	/**
	 * 删除留言
	 */
	public Boolean deleteMessage(Message message) throws Exception {
		try {
			message.setStatementName("deleteMessage");
			messageDao.delete(message);
			return true;
		} catch (RuntimeException e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}
}
